package com.ruoyi.project.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

@Component
public class MailUtil {

    /**
     * 注入邮件工具类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;


    /**
     * 发送本地文件
     * @param subject
     * @param content
     * @param contentIsHtml
     * @param fromMailPersonalName
     * @param toMail
     * @param ccMail
     * @param bccMail
     * @param fileName
     * @param fileInput
     * @param sendUsername
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public void sendEmail(String subject, String content, boolean contentIsHtml, String fromMailPersonalName,
                                 String toMail, String ccMail, String bccMail, String fileName, InputStreamSource fileInput, String sendUsername) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(sendUsername, fromMailPersonalName);
        helper.setTo(toMail);
        if (!ObjectUtils.isEmpty(ccMail)) {
            helper.setCc(ccMail);
        }
        if (!ObjectUtils.isEmpty(bccMail)) {
            helper.setBcc(bccMail);
        }
        helper.setSubject(subject);
        helper.setText(content, contentIsHtml);
        // 设置附件（注意这里的fileName必须是服务器本地文件名，不能是远程文件链接）
        if (fileInput != null) {
            helper.addAttachment(fileName, fileInput);
        }
        javaMailSender.send(message);
    }

}